package com.zhkj.txg.wxapi

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.R
import com.zhkj.lib.config.WX_APP_ID
import com.zhkj.txg.utils.PayResult
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelpay.PayResp
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

class WXPayEntryActivity : Activity(), IWXAPIEventHandler {

    private lateinit var api: IWXAPI

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID)
        api.handleIntent(intent, this)
    }

    override fun onResp(resp: BaseResp?) {
        finish()
        if (resp?.type == ConstantsAPI.COMMAND_PAY_BY_WX) { //  微信支付
            (resp as? PayResp)?.let {
                when (it.errCode) {
                    // 支付成功
                    BaseResp.ErrCode.ERR_OK -> {
                        val result = PayResult(true, getString(R.string.pay_success), it.extData.toInt())
                        // 发送支付结果，通知页面需要刷新
                        RxBus.post(result)
                    }
                    // 用户取消
                    BaseResp.ErrCode.ERR_USER_CANCEL -> RxBus.post(PayResult(false, it.errStr))
                    // 支付失败
                    else -> RxBus.post(PayResult(false, it.errStr))
                }
            }
        }
    }

    override fun onReq(req: BaseReq?) = Unit

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        api.handleIntent(intent, this)
    }
}